import { Card, Col, Form, Row, Steps } from 'antd';
import { useModel } from '@umijs/max';
import { useEmotionCss } from '@ant-design/use-emotion-css';
import StepOnePage from './stepOne';
import StepTwoPage from './stepTwo';
import StepThreePage from './stepThree';
import StepFourPage from './stepFour';
import StepFivePage from './stepFive';
import SetpNewFour from './setpNewFour';
import { useEffect, useState } from 'react';
import { companyReports, demand, getProgram, situation } from '@/services/apis/companyRegister';
import dayjs from 'dayjs';

const stepTitles = ['企业注册', '数字化改造需求', '数字化改造情况', '项目实施', '项目验收'];

const STATUS_OPTIONS: any = {
  "noStart": "未开始",
  'pending': "待审核",
  "approved": "已通过",
  "rejected": "不通过",
  "returned": "已退回"
}
const SETP_STATUS: any = {
  "pending": "process",
  "approved": "finish",
  "returned": "error",
  "noStart": "wait"
}
const STATUS_OPTIONS_REGISTER: any = {
  "2": "已注册",
  "1": "待注册",
}

const PROGARM_STATUS: any = {
  "edit": "已填写",
  "noedit": "待填写"
}
const PROGARM_STATUS_STEP: any = {
  "edit": "finish",
  "noedit": "wait"
}

const DigitalizationProductPage: React.FC = () => {
  const { stepProps, setStepProps } = useModel('DigitalizationManager.stepProps');
  const { initialState, setInitialState } = useModel('@@initialState');
  const { dataGlobal, setDataGlobal } = useModel('DigitalizationManager.dataGlobal');
  const [items, setItems] = useState<any[]>([])

  const stepOnchange = (step: number) => {
    setStepProps((prev) => ({ ...stepProps, current: step }));
  };

  const onFinish = (values: any) => { };
  const onFinishFailed = (values: any) => { };
  const dataInit = async () => {
    const stepTwoResult = await demand({ companyId: (initialState?.currentUser as any).data.id })
    const { code, data } = stepTwoResult;
    const formData = code == "0" && data.scenesData?.reduce((pre: { [x: string]: any; }, cur: { label: string | number; scenes: any; }) => {
      pre[cur.label] = cur.scenes
      return pre
    }, {})
    const stepThreeResult = await situation({ companyId: (initialState?.currentUser as any).data.id })
    const { code: threeCode, data: threeData } = stepThreeResult;
    const hetongL: { [key: string]: any } = {}
    const serviceAndProduct: any[] = []
    if (threeCode == "0") {
      threeData.digitalContentList = threeData.digitalContentList?.map((item: { programEnd: any; programStart: any; }) =>
        ({ ...item, programEnd: dayjs(item.programEnd), programStart: dayjs(item.programStart) }))

      threeData.digitalContentList?.forEach((item: any, index: any) => {
        const key = ["digitalContentList", index, 'changeContract'].join("_")
        hetongL[key] = item.changeContract?.map((fileItem: any) =>
          ({ ...fileItem, name: fileItem.filename, uid: Math.random().toString() }))
        item.connectService.forEach((itemService: any, indexService: string | number) => {
          serviceAndProduct.push({ connectProvider: itemService, dealWayName: item.productName[indexService] })
        })
      })
    }
    const programData = await getProgram({ companyId: (initialState?.currentUser as any).data.id });
    const { code: fourCode, data: fourData } = programData;
    const fourDataItem = fourCode == "0" && fourData[0]

    const fiveDataAll = threeData?.companyId ? 
    await companyReports({ companyId: threeData.companyId, projectId: threeData.projectId }) : {code:-1,data:{}}
    const { code: fiveCode, data: fiveData } = fiveDataAll;
    const fiveDataItem = fiveCode == "0" ? fiveData : {}
    setDataGlobal({
      stepTwo: formData,
      setpThree: threeData,
      threeHetong: hetongL,
      stepTwoDisabled: (data?.resultStatus?.includes("通过") && !data?.resultStatus?.includes("不通过"))
        || data?.resultStatus?.includes("待县（市、区）经商局审核") || data?.resultStatus?.includes("待市经信局审核"),
      stepThreeDisabled: (threeData?.resultStatus?.includes("通过") && !threeData?.resultStatus?.includes("不通过"))
        || threeData?.resultStatus?.includes("待县（市、区）经商局审核") || threeData?.resultStatus?.includes("待市经信局审核"),
      stepFourData: fourDataItem,
      setpFourDisabled: fourDataItem ? fourDataItem?.edit == "1" : !(data?.resultStatus?.includes("审核通过") && threeData?.resultStatus?.includes("审核通过")),
      stepFiveData: serviceAndProduct,
      fiveDataAll: fiveData,
      stepFiveDisabled: fiveDataItem && fiveDataItem?.edit == "1"
    })
    const items = stepTitles.map((title, index) => {
      let description, status, disabled = false;
      switch (title) {
        case "企业注册":
          description = STATUS_OPTIONS_REGISTER["2"]
          status = "finish"
          break;
        case "数字化改造需求":
          if (data?.resultStatus) {
            description = data?.resultStatus
            if (data?.resultStatus?.includes("通过") && !data?.resultStatus?.includes("不通过")) {
              status = "finish"
            } else if (data?.resultStatus?.includes("不通过")) {
              status = "error"
            } else {
              status = "process"
            }
          } else {
            description = "待填写"
            status = "wait"
          }

          break
        case "数字化改造情况":
          if (threeData?.resultStatus) {
            description = threeData?.resultStatus
            if (threeData?.resultStatus?.includes("通过") && !threeData?.resultStatus?.includes("不通过")) {
              status = "finish"
            } else if (threeData?.resultStatus?.includes("不通过")) {
              status = "error"
            } else {
              status = "process"
            }
          } else {
            description = "待填写"
            status = "wait"
          }

          break
        case "项目实施":
          const isWrite = fourDataItem ? Object.keys(fourDataItem).some(item =>
            ["isPerformanceEvaluated", "isRunning", "isThrough"].includes(item) && fourDataItem[item]) : false
          description = isWrite ? PROGARM_STATUS["edit"] : PROGARM_STATUS["noedit"]
          status = isWrite ? PROGARM_STATUS_STEP["edit"] : PROGARM_STATUS_STEP["noedit"]
          if (!data?.resultStatus || !threeData?.resultStatus
            || (data?.resultStatus.startsWith("待") && data?.resultStatus.endsWith("审核"))) {
            disabled = true
          }
          break
        case "项目验收":
          const isEdit = fiveDataItem?.edit == "1";
          description = isEdit ? PROGARM_STATUS["edit"] : PROGARM_STATUS["noedit"]
          status = isEdit ?  PROGARM_STATUS_STEP["edit"] : PROGARM_STATUS_STEP["noedit"]
          if (!data?.resultStatus || !threeData?.resultStatus || (data?.resultStatus.startsWith("待") && data?.resultStatus.endsWith("审核"))) {
            disabled = true
          }
          break
        default:
          description = STATUS_OPTIONS["noStart"]
          status = SETP_STATUS["noStart"]
          if (!data?.resultStatus || !threeData?.resultStatus || (data?.resultStatus.startsWith("待") && data?.resultStatus.endsWith("审核"))) {
            disabled = true
          }
      }
      return {
        title,
        description,
        status,
        disabled
        // disabled:title == "绩效评价" && initialState?.currentUser?.access == "enterprise"
      }
    });
    setItems(items)
    setStepProps(prev => ({ ...prev, current: 1 }))
  }
  useEffect(() => {
    dataInit()
  }, [])


  return (
    <div
      style={{
        height: '100vh',
        display: 'flex',
        flexDirection: 'column',
      }}
    >
      {/* 固定步骤条 */}
      <div
        style={{
          position: 'sticky',
          top: 0,
          zIndex: 100,
          background: '#fff',
          padding: '16px 0',
        }}
      >
        <Row justify="center">
          <Col span={20}>
            <Steps
              size='small'
              // className={noWrapCls}
              onChange={stepOnchange}
              current={stepProps.current}
              items={items as any}
            />
          </Col>
        </Row>
      </div>

      {/* Card 内容区域：固定高度 + 内部滚动 */}
      <Card
        style={{
          margin: '16px',
          borderRadius: 12,
          boxShadow: '0 2px 8px rgba(0,0,0,0.06)',
          height: 'calc(100vh - 120px)', // 精确高度，保证内部滚动
          overflowY: 'auto', // 内部滚动
          padding: '24px',
        }}
      // bodyStyle={{
      //   padding: '24px',
      // }}
      >
        <Row justify="center">
          <Col span={20}>
            <Form
              name="basic"
              layout="horizontal"
              labelAlign="left"
              wrapperCol={{ span: 18 }}
              style={{ width: '100%' }}
              initialValues={{ remember: true }}
              onFinish={onFinish}
              onFinishFailed={onFinishFailed}
              autoComplete="off"
            // className={leftLabelCls}
            >
              {stepProps.current === 0 && <StepOnePage />}
              {stepProps.current === 1 && <StepTwoPage />}
              {stepProps.current === 2 && <StepThreePage />}
              {stepProps.current === 3 && <SetpNewFour />}
              {stepProps.current === 4 && <StepFourPage />}
            </Form>
          </Col>
        </Row>
      </Card>
    </div>
  );
};

export default DigitalizationProductPage;
